package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class IWechatServiceImpl implements IWechatService {

    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    private final static String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private final static String PHOEN_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Override
    public String getOpenId(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.get(OPEN_ID_URL, map);
        log.info("获取微信openid接日返回:{}", response);
        JSON parse = JSONUtil.parse(response);
        String openid = parse.getByPath("openid") + "";
        return openid;
    }



    private String getToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("grant_type", "client_credential");
        String response = HttpUtil.get(TOKEN_URL, map);
        log.info("获取token返回:{}", response);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject.getStr("access_token");
    }

    @Override
    public String getPhone(String phoneCode) {
        String url = PHOEN_URL + getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);
        String response = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        log.info("获取手机号返回:{}", response);
        JSON parse = JSONUtil.parse(response);
        String phone = parse.getByPath( "phone_info.phoneNumber") + "";
        return phone;
    }


}
